#include "sem.hpp"
#include "task.hpp"
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
std::string SelfName()
{
    char name[128];
    snprintf(name, sizeof(name), "thread[0x%x]", pthread_self());
    return name;
}
void *ProductorRoutine(void *rq)
{
    RingQueue<Task> *ringqueue = static_cast<RingQueue<Task> *>(rq);
    while (true)
    {
        int x = rand() % 10;
        int y = rand() % 5;
        char op = oper[rand() % oper.size()];
        Task t(x, y, op, mymath);
        ringqueue->Push(t);
        printf("%s, 生产者派发了一个任务: %s\n", SelfName().c_str(), t.toTaskString().c_str());
        sleep(1);
    }
}
void *ConsumerRoutine(void *rq)
{
    RingQueue<Task> *ringqueue = static_cast<RingQueue<Task> *>(rq);
    while (true)
    {
        Task t;
        ringqueue->Pop(&t);
        std::string result = t();
        printf("%s,消费者消费了一个任务: %s\n", SelfName().c_str(), result.c_str());
        // sleep(1);
    }
}
int main()
{
    srand((unsigned int)time(nullptr) ^ getpid() ^ pthread_self() ^ 0x71727374);
    RingQueue<Task> *rq = new RingQueue<Task>();
    // 多生产多消费只需保持最终进入临界区的是一个生产者一个消费者就行了
    pthread_t p[4], c[8];
    for (int i = 0; i < 4; i++)
    {
        pthread_create(p + i, nullptr, ProductorRoutine, rq);
    }
    for (int i = 0; i < 8; i++)
    {
        pthread_create(c + i, nullptr, ConsumerRoutine, rq);
    }
    for (int i = 0; i < 4; i++)
    {
        pthread_join(p[i], nullptr);
    }
    for (int i = 0; i < 8; i++)
    {
        pthread_join(c[i], nullptr);
    }
    delete rq;
    return 0;
}